package person.bluext.singlegateway.helper;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description : Application context helper
 *
 * @author : bluext
 */
@Component
public class ApplicationContextHelper implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException {
        applicationContext = _applicationContext;
    }

    /**
     * get bean by name
     *
     * @param beanName name of bean
     * @return bean
     */
    public Object getBean(String beanName) {
        return this.applicationContext.getBean(beanName);
    }

    /**
     * get bean of type
     *
     * @param clazz bean type
     * @return bean
     */
    public <T> T getBeanOfType(Class<T> clazz) {
        Map<String, T> resultMap = this.applicationContext.getBeansOfType(clazz);
        for (String key : resultMap.keySet()) {
            if (key.equalsIgnoreCase(clazz.getSimpleName())) {
                return resultMap.get(key);
            }
        }
        return null;
    }
}
